package secondriver.heathfood.client;

import android.content.Context;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import secondriver.heathfood.bean.FoodClass;
import secondriver.heathfood.bean.FoodDetail;
import secondriver.heathfood.util.SimpleDiskCache;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Author : secondriver
 */
public class ApiClient {

    static final String CLASSIFY = Constants.SERVER + "/api/cook/classify?id=%d";
    //    static final String FOOD_DETAIL_BY_NAME = Constants.SERVER + "/api/cook/name?name=%s";
    static final String FOOD_DETAIL_BY_ID = Constants.SERVER + "/api/cook/show?id=%d";
    static final String FOOD_DETAIL_LIST_FOR_PAGE = Constants.SERVER + "/api/cook/list?id=%d&page=%d&rows=%d";

    private static final ConcurrentHashMap<String, ApiClient> cacheApiClient = new ConcurrentHashMap<String, ApiClient>(2);

    public final SimpleDiskCache simpleDiskCache;

    private ApiClient(SimpleDiskCache simpleDiskCache) {
        this.simpleDiskCache = simpleDiskCache;
    }

    public static ApiClient build(Context ctx, String name) {
        if (cacheApiClient.containsKey(name)) {
            return cacheApiClient.get(name);
        } else {
            ApiClient mApiClient = new ApiClient(new SimpleDiskCache(ctx, name));
            cacheApiClient.put(name, mApiClient);
            return mApiClient;
        }
    }

    public SimpleDiskCache getSimpleDiskCache() {
        return simpleDiskCache;
    }


    /**
     * 通过ID查询食物详细信息
     *
     * @param id 食物信息编号 正整数
     * @return
     */
    public FoodDetail getFoodDetailById(long id) {
        return getFoodDetail(String.format(FOOD_DETAIL_BY_ID, id));
    }

//    public static FoodDetail getFoodDetailByName(String name) {
//        return getFoodDetail(String.format(FOOD_DETAIL_BY_NAME, name));
//    }

    /**
     * 通过食物类别ID分页查询食物简介信息
     *
     * @param id
     * @param page
     * @param rows
     * @return
     */
    public List<FoodDetail> getFoodBriefForPage(int id, int page, int rows) {
        if (page < 1) {
            page = Constants.DEFAULT_PAGE_INDEX;
        }
        if (rows < 1) {
            rows = Constants.DEFAULT_PAGE_ROWS;
        }
        String foodDetailContent = getContent(String.format(FOOD_DETAIL_LIST_FOR_PAGE, id, page, rows));
        return jsonConvertFoodDetailCollection(foodDetailContent);
    }

    /**
     * 通过食物类别ID查询食物分类信息JSON格式
     *
     * @param id 食物分类ID
     * @return
     */
    public String getFoodClassContent(long id) {
        if (id < 0) {
            id = Constants.CLASSIFY_ROOT;
        }
        String classifyContent = "";
        String key = String.valueOf(id);
        if (simpleDiskCache.isExistInPreference(key)) {
            classifyContent = simpleDiskCache.getFromPreference(key);
        } else {
            classifyContent = getContent(String.format(CLASSIFY, id));
            simpleDiskCache.putToPreference(key, classifyContent);
        }
        return classifyContent;
    }

    public static List<FoodClass> jsonConvertFoodClassCollection(String json) {
        if (json != null && !json.equals("")) {
            JSONObject jsonObject = JSON.parseObject(json);
            JSONArray jsonArray = jsonObject.getJSONArray("tngou");//{"status":true,tngou:[{},{}]}
            String content = jsonArray.toJSONString();
            return JSONArray.parseArray(content, FoodClass
                    .class);
        } else {
            return Collections.EMPTY_LIST;
        }
    }

    public static String FoodDetailConvertJson(FoodDetail foodDetail) {
        return JSONObject.toJSONString(foodDetail);
    }

    public static List<FoodDetail> jsonConvertFoodDetailCollection(String json) {
        if (json != null && !json.equals("")) {
            JSONObject jsonObject = JSON.parseObject(json);
//            long total = jsonObject.getLongValue("total");  //{"status":true,"total":11,tngou:[{},{}]}
            JSONArray jsonArray = jsonObject.getJSONArray("tngou");
            String content = jsonArray.toJSONString();
            return JSONArray.parseArray(content, FoodDetail.class);
        } else {
            return Collections.EMPTY_LIST;
        }
    }



    private static FoodDetail getFoodDetail(String url) {
        String foodDetailContent = getContent(url);
        if (foodDetailContent != null) {
            return JSONObject.parseObject(foodDetailContent, FoodDetail.class);
        } else {
            return FoodDetail.Null;
        }
    }

    public static String getContent(String url) {
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse response = client.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toString(entity);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
}